package org.eiahe.hr.interview.controller;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.BaseController;
import org.ehe.common.core.domain.R;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.eiahe.hr.interview.domain.InterviewQuestionBank;
import org.eiahe.hr.interview.domain.InterviewRecord;
import org.eiahe.hr.interview.domain.vo.InterviewRecordVO;
import org.eiahe.hr.interview.domain.dto.InterviewRecordDTO;
import org.eiahe.hr.interview.domain.dto.InterviewRecordResultDTO;
import org.eiahe.hr.interview.service.InterviewBehaviorTestRecordsService;
import org.eiahe.hr.interview.service.InterviewQuestionBankService;
import org.eiahe.hr.interview.service.InterviewRecordService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

/**
 * 面试记录
 * @author :zhangnn
 * @className :InterviewRecordController
 * @description: TODO
 * @date 2025-08-14 09:48:24
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/interview/record")
public class InterviewRecordController extends BaseController {

    private final InterviewRecordService interviewRecordService;
    private final InterviewQuestionBankService bankService;
    private final InterviewBehaviorTestRecordsService behaviorTestRecordsService;

    /**
     * 分页
     */
    @GetMapping("/page")
    public TableDataInfo<InterviewRecordVO> list(InterviewRecordDTO queryDTO, PageQuery pageQuery) {
        TableDataInfo<InterviewRecordVO> page = interviewRecordService.selectRecordPage(queryDTO,pageQuery);
        return page;
    }


    /**
     * 根据ID查询面试记录详情
     * @param id
     * @param flag 面试标识
     * @return
     */
    @GetMapping("/{id}/{flag}")
    public R<InterviewRecordVO> getById(@PathVariable("id") Long id, @PathVariable("flag") String flag) {
        InterviewRecordVO record = interviewRecordService.detail(id,flag);
        return R.ok(record);
    }

    /**
     * 新增面试记录
     */
    @Log(title = "面试新增", linkType = "interview", businessType = BusinessType.INSERT, idField = "name")
    @PostMapping
    public R<Void> add(@Valid @RequestBody InterviewRecordDTO dto) {
        boolean result = interviewRecordService.insertRecord(dto);
        return result ? R.ok() : R.fail("新增失败");
    }

    /**
     * 修改面试记录
     */
    @Log(title = "面试信息更新", linkType = "interview", businessType = BusinessType.UPDATE, idField = "name")
    @PostMapping("/{id}")
    public R<Void> edit(@PathVariable("id") Long id, @Valid @RequestBody InterviewRecordDTO dto) {
        boolean result = interviewRecordService.updateRecord(id, dto);
        return result ? R.ok() : R.fail("修改失败");
    }

    /**
     * 删除面试记录
     */
    @Log(title = "面试信息删除", linkType = "interview", businessType = BusinessType.DELETE,  nameField = "name")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@PathVariable("ids") String ids) {
        String[] idArray = ids.split(",");
        boolean result = interviewRecordService.deleteByIds(Arrays.asList(idArray));
        return result ? R.ok() : R.fail("删除失败");
    }

    /**
     * 上传简历并识别信息
     * 支持PDF、DOC、DOCX格式
     */
    @Log(title = "面试简历识别", linkType = "interview", businessType = BusinessType.OTHER, idField = "name")
    @PostMapping("/upload-resume")
    public R<InterviewRecordDTO> uploadResume(@RequestParam("file") MultipartFile file,
                                              @RequestParam(value = "categoryId", required = false) Long categoryId) {
        try {
            // 验证文件类型
            if (!isValidResumeFile(file)) {
                return R.fail("不支持的文件格式，仅支持PDF、DOC、DOCX格式");
            }
            // 解析简历并返回候选人信息
            InterviewRecordDTO recordDTO = interviewRecordService.parseResumeAndCreateRecord(file, categoryId);
            return R.ok(recordDTO);

        } catch (Exception e) {
            log.error("简历上传解析失败", e);
            return R.fail("简历上传解析失败：" + e.getMessage());
        }
    }

    /**
     * 更新面试状态
     */
    @Log(title = "面试状态更新", linkType = "interview", businessType = BusinessType.UPDATE, idField = "id", nameField = "status")
    @PostMapping("/{id}/status")
    public R<InterviewRecord> updateStatus(@PathVariable("id") Long id, @RequestParam("status") Integer status) {
        InterviewRecord record = new InterviewRecord();
        boolean result = interviewRecordService.updateInterviewStatus(id, status);
        if(result){
            record = interviewRecordService.getById(id);
        }
        return result ? R.ok(record) : R.fail("状态更新失败");
    }


    /**
     * 更新面试结果
     * @param recordDTO
     * @return
     */
    @Log(title = "面试结果更新", linkType = "interview", businessType = BusinessType.UPDATE, idField = "id", nameField = "categoryName")
    @PostMapping("/updateResult")
    public R<Void> updateResult(@RequestBody InterviewRecordResultDTO recordDTO) {
        if(recordDTO.getBankId() != null){
            InterviewQuestionBank bank = bankService.getById(recordDTO.getBankId());
            if(bank.getInterviewType() == 2){
                boolean success =  behaviorTestRecordsService.insertTestRecords(recordDTO);
                return success ? R.ok() : R.fail("结果更新失败");
            }
        }

        boolean success = interviewRecordService.updateInterviewResult(recordDTO);
        return success ? R.ok() : R.fail("结果更新失败");
    }

    /**
     * 更新录用状态
     */
    @Log(title = "面试录用状态更新", linkType = "interview", businessType = BusinessType.UPDATE, idField = "id", nameField = "isHired")
    @PostMapping("/{id}/hire")
    public R<InterviewRecord> updateHireStatus(@PathVariable("id") Long id, @RequestParam("isHired") Integer isHired) {
        InterviewRecord record = new InterviewRecord();
        boolean result = interviewRecordService.updateHireStatus(id, isHired);
        if(result){
            record = interviewRecordService.getById(id);
        }
        return result ? R.ok(record) : R.fail("录用状态更新失败");
    }

    /**
     * 验证是否为有效的简历文件格式
     */
    private boolean isValidResumeFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return false;
        }

        String extension = originalFilename.toLowerCase();
        return extension.endsWith(".pdf") ||
            extension.endsWith(".doc") ||
            extension.endsWith(".docx");
    }


}
